#!/usr/bin/python 
# -*- coding: utf-8 -*-

"""


This program is an utility in order to
manage MADS data base

author: Francesco di Dio, Simone Pasculli
last edited: february 2014
"""

import sys
from PySide import QtGui
from PySide.QtCore import *
from PySide.QtGui import *
import operator
import madsloader
import madsutil
import thread,threading



class MadsConfigApp(QtGui.QMainWindow):
    
    def __init__(self):
        super(MadsConfigApp, self).__init__()
        self.current_table_page = 1
        self.element_for_page = 10
        self.cards = {}
        self.initUI()
        
    def load_keyword_action(self):
        self.text_editor.clear()
        worker = madsloader.LoadKeyWordsWorker(self.text_editor)
        #worker.addAppender(self.text_editor)
        thread.start_new_thread(worker.run, ())
        print 'load keyword exit'
        #t1 = threading.Thread(target=madsloader.load_keywords, args = ([self.text_editor]))
        #t1.start()
        #t1.join()
        
    def load_card_action(self):
        self.text_editor.clear()
        worker = madsloader.LoadCardsWorker(appender=self.text_editor)
        thread.start_new_thread(worker.run, ())
    
    def refresh_cards(self):
        self.cards = madsloader.get_cards(self.current_table_page, self.element_for_page)
        self.table_model.mylist = self.cards
        self.table_view.resizeColumnsToContents()
        self.table_view.update();
        self.table_model.update()
    
    def next_cards(self):
        self.current_table_page+=1
        self.cards = madsloader.get_cards(self.current_table_page, self.element_for_page)
        self.table_model.mylist = self.cards
        self.table_view.resizeColumnsToContents()
        self.table_view.update();
        self.table_model.update()
    
    def prev_cards(self):
        if(self.current_table_page>1):
            self.current_table_page-=1
        self.cards = madsloader.get_cards(self.current_table_page, self.element_for_page)
        self.table_model.mylist = self.cards
        self.table_view.resizeColumnsToContents()
        self.table_view.update();
        self.table_model.update()
       
        

    def show_parameter_action(self):
        self.text_editor.clear()
        madsutil.log('LIB_VERSION=' + madsutil.LIB_VERSION,self.text_editor)
        madsutil.log('GUI_VERSION=' + madsutil.GUI_CONF_VERSION,self.text_editor)
        madsutil.log('DB NAME=' + madsutil.DB_NAME,self.text_editor)
        madsutil.log('DB URL=' + madsutil.DB_URL,self.text_editor)
        madsutil.log('HEADERS=' + str(madsutil.HEADERS),self.text_editor)
        madsutil.log('*** STATS ***' ,self.text_editor)
        
        
        
    def initUI(self):               
        layout = QVBoxLayout()
        centralFrame = QtGui.QWidget()
        exitAction = QtGui.QAction(QtGui.QIcon('imgs/exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)
        
        loadKeyWrdsAction = QtGui.QAction(QtGui.QIcon('imgs/keys.png'), '&LoadKeyWord', self)
        loadKeyWrdsAction.setShortcut('Ctrl+K')
        loadKeyWrdsAction.setStatusTip('Load Key Words')
        loadKeyWrdsAction.triggered.connect(self.load_keyword_action)
        
        showParamsAction = QtGui.QAction(QtGui.QIcon('imgs/cfg.png'), '&ShowParam', self)
        showParamsAction.setShortcut('Ctrl+P')
        showParamsAction.setStatusTip('Show parameters')
        showParamsAction.triggered.connect(self.show_parameter_action)
        
        loadCardAction = QtGui.QAction(QtGui.QIcon('imgs/cardloader.png'), '&LoadCards', self)
        loadCardAction.setShortcut('Ctrl+L')
        loadCardAction.setStatusTip('Card Loader')
        loadCardAction.triggered.connect(self.load_card_action)
        
        refreshCardsAction = QtGui.QAction(QtGui.QIcon('imgs/refresh.png'), '&Refresh', self)
        refreshCardsAction.setShortcut('Ctrl+R')
        refreshCardsAction.setStatusTip('Refresh Table')
        refreshCardsAction.triggered.connect(self.refresh_cards)

        nextCardsAction = QtGui.QAction(QtGui.QIcon('imgs/next.png'), '&Next', self)
        nextCardsAction.setShortcut('Ctrl+N')
        nextCardsAction.setStatusTip('Next page Table')
        nextCardsAction.triggered.connect(self.next_cards)        

        prevCardsAction = QtGui.QAction(QtGui.QIcon('imgs/prev.png'), '&Prev', self)
        prevCardsAction.setShortcut('Ctrl+P')
        prevCardsAction.setStatusTip('Previusly page Table')
        prevCardsAction.triggered.connect(self.prev_cards)   
        
        self.table_model = CardTableModel(self, self.cards, ['name','link','gatherer_page'])
        self.table_view = QTableView()
        self.table_view.setModel(self.table_model)
        self.table_view.resizeColumnsToContents()
        layout.addWidget(self.table_view)
        
        self.text_editor = QTextEdit()
        self.text_editor.setReadOnly(True)
        layout.addWidget(self.text_editor)
        centralFrame.setLayout(layout)
        self.setCentralWidget(centralFrame)
        

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        
        
        self.toolbar = self.addToolBar('Toolbar')
        self.toolbar.addAction(exitAction)
        self.toolbar.addAction(loadKeyWrdsAction)
        self.toolbar.addAction(showParamsAction)
        self.toolbar.addAction(loadCardAction)
        self.toolbar.addAction(prevCardsAction)
        self.toolbar.addAction(refreshCardsAction)
        self.toolbar.addAction(nextCardsAction)
        
        self.setGeometry(200, 200, 750, 350)
        self.setWindowTitle('M.A.D.S. Configurator v. ' + madsutil.GUI_CONF_VERSION)

        #sys.stdout = madsutil.OutLog( self.text_editor, sys.stdout)
        #sys.stderr = madsutil.OutLog( self.text_editor, sys.stderr, QtGui.QColor(255,0,0) )    
        self.show()

class StdOutWrapper(object):
    
    def setWidget(self,wid):
        self._wid = wid
    
    def write(self, text):
        self._wid.append(text.strip())

class CardTableModel(QAbstractTableModel):
    def __init__(self, parent, mylist, header, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.mylist = mylist
        self.header = header
    def rowCount(self, parent):
        return len(self.mylist)
    def columnCount(self, parent):
        return len(self.header)
    
    def update(self):
        self.emit(SIGNAL("dataChanged()"))
        self.emit(SIGNAL("layoutChanged()"))
    
    def data(self, index, role):
        if not index.isValid():
            return None
        elif role != Qt.DisplayRole:
            return None
        elif index.column()>= len(self.header):
            return None
        col = self.header[index.column()]        
        return self.mylist[index.row()].get(col)
    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole and col<len(self.header):
            return self.header[col]
        return None
    def sort(self, col, order):
        """sort table by given column number col"""
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.mylist = sorted(self.mylist,
            key=operator.itemgetter(col))
        if order == Qt.DescendingOrder:
            self.mylist.reverse()
        self.emit(SIGNAL("layoutChanged()"))
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    madsApp = MadsConfigApp()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

'''restore std output

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

'''

